package summer.tree;

public class Solution106 {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return build(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }

    public TreeNode build(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) {
        if (inStart > inEnd || postStart > postEnd) return null;
        TreeNode root = new TreeNode(postorder[postEnd]);
        if (inStart == inEnd) return root;
        int index = findRoot(inorder, inStart, inEnd, root.val);
        root.left = build(inorder, inStart, index - 1, postorder, postStart, postStart + index - inStart - 1);
        root.right = build(inorder, index + 1, inEnd, postorder, postStart + index - inStart, postEnd - 1);
        return root;
    }

    public int findRoot(int[] nums, int start, int end, int target) {
        for (int i = start; i < end + 1; i++) {
            if (nums[i] == target) return i;
        }
        return -1;
    }
}
